import { createStore } from "vuex";
import { info, login } from "@/api/user";

export default createStore({
  // 存储数据
  state: {
    // 系统当前登录的用户信息
    user: JSON.parse(window.sessionStorage.getItem("user")),
  },
  getters: {
    /**
     * 获取用户信息
     */
    getUser(state) {
      return state.user;
    },
  },
  mutations: {
    /**
     * 存储登录用户的信息
     */
    setUser(state, user) {
      state.user = user;
    },

    /**
     * 删除登录用户的信息
     */
    removeUser(state) {
      state.user = null;
    },
  },
  actions: {
    /**
     * 存储用户信息
     */
    async refreshUserInfo(state) {
      const responsee = await info();
      const data = responsee.data.data;
      state.commit("setUser", data);
      window.sessionStorage.setItem("user", JSON.stringify(data));
    },

    /**
     * 登出
     */
    async logout(state) {
      // 删除浏览器本地缓存
      //window.localStorage.removeItem("user");
      window.sessionStorage.removeItem("token");
      window.sessionStorage.removeItem("user");
      state.commit("removeUser");
    },

    /**
     * 登录
     */
    async userLogin({ dispatch }, token) {
      window.sessionStorage.setItem("token", token);
      dispatch("refreshUserInfo");
      // await refreshUserInfo();
    },
  },
});
